package com.taotao.job.rpc.sofabolt;

import com.alipay.remoting.rpc.RpcClient;
import com.taotao.job.rpc.core.meta.IfaceMeta;
import com.taotao.job.rpc.invoker.RpcRemoteException;
import com.taotao.job.rpc.invoker.caller.RemoteCaller;
import com.taotao.job.rpc.invoker.caller.RequestData;
import com.taotao.job.rpc.invoker.caller.ResponseData;

/**
 * @author fanbeibei
 * @date 2021/4/4 9:49
 */
public class SofaboltRemoteCaller implements RemoteCaller {
    private RpcClient client = new RpcClient();

    public SofaboltRemoteCaller() {
        client.startup();
    }


    @Override
    public <T> T callRemote(String address, IfaceMeta ifaceMeta, Object[] args, Class<T> expectResultClass, long timeoutMillis) throws RpcRemoteException {
        RequestData reqData = new RequestData(ifaceMeta, args);

        try {
            ResponseData respData = (ResponseData) client.invokeSync(address, reqData, (int) timeoutMillis);
            if (ResponseData.CODE_SUCCESS != respData.getCode()) {
                throw new RpcRemoteException(respData.getMsg());
            }

            return (T) respData.getData();
        } catch (Exception e) {
            throw new RpcRemoteException(e);
        }

    }
}
